<?php
namespace app\index\controller;

use think\Controller;
use app\common\ErrorReports;

class Index extends Controller
{
    private static $RELATION = [
        'bread' => '面包',
        'dairy_product' => '乳制品',
        'dessert' => '甜点',
        'egg' => '鸡蛋',
        'fried_food' => '油炸食品',
        'meat' => '肉类',
        'noodles_and_pasta' => '面条和意大利面',
        'rice' => '米饭',
        'seafood' => '海鲜',
        'soup' => '汤',
        'vegetable_and_fruit' => '蔬菜和水果'
    ];

    /**
     * 首页
     */
    public function index()
    {
        return view();
    }

    /**
     * 文件上传
     */
    public function uploads()
    {
        // 上传文件
        $file = request()->file('file');
        $info = $file->validate(['size' => 2097152, 'ext' => 'jpg'])->move('uploads', true);
        if ($info) {
            $path = $info->getSaveName();
        } else {
            error($file->getError());
        }
        return success(['path' => $path]);
    }

    /**
     * 图片分析
     */
    public function classify()
    {
        // 分析图片
        ini_set('max_execution_time', '0');
        $path = input('path');
        $res1 = `python classify.py --model_path static/graph1.pb --label_path static/label1.txt --image_file uploads/{$path}`;
        $res1 = explode('*&^', $res1);
        $res = $res1[1];
        if ($res == 0) {
            $result = '非食品';
            $score = $res1[2];
        } else {
            $res2 = `python classify.py --model_path static/graph2.pb --label_path static/label2.txt --image_file uploads/{$path}`;
            $res2 = explode('*&^', $res2);
            $res = $res2[1];
            $result = static::$RELATION[$res];
            $score = $res2[2];
        }
        return success(['result' => $result, 'score' => $score]);
    }

    /**
     * miss
     */
    public function miss()
    {
        error('Sorry, but the resource you are looking for is not existed!');
    }

    /**
     * 所有错误报告
     */
    public function getReportList()
    {
        echo ErrorReports::getReportList();
    }

    /**
     * 单条错误报告
     */
    public function getReport($id)
    {
        echo ErrorReports::getReportById($id);
    }
}
